package com.hy.bean;

import com.hy.corecode.idgen.IdGenerator;
import com.hy.corecode.idgen.WFGIdGenerator;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.event.EventListener;

/**
 * @author: 王富贵
 * @description: 支持动态配置的静态id生成器
 * @createTime: 2023/9/4 18:41
 */
public class RefreshIdGeneratorListener implements BeanFactoryAware, ApplicationContextAware {

    private ListableBeanFactory beanFactory;
    private ApplicationContext applicationContext;

    /**
     * 监听器: 该事件位于获取远端配置之后，接受servlet之前
     * 从上下文获取的对象，在cloud中如果使用@RefreshSCope会拿到代理对象。
     * 该注解会创建一个真正使用的bean map持有在bean中，当触发刷新事件会清空真正使用的bean map，重新创建真正使用的bean
     * 故只需要启动的时候获取代理bean给到静态类即可
     *
     * @param event
     */
    @EventListener(classes = ApplicationPreparedEvent.class)
    public void listenApplicationPreparedEvent(ApplicationPreparedEvent event) {
        WFGIdGenerator idGenerator = applicationContext.getBean(WFGIdGenerator.class);
        IdGenerator.setWfgIdGenerator(idGenerator);
    }

    /**
     * 获取上下文容器
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 获取beanFactory
     *
     * @param beanFactory owning BeanFactory (never {@code null}).
     *                    The bean can immediately call methods on the factory.
     * @throws BeansException
     */
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (ListableBeanFactory) beanFactory;
    }

    /**
     * 获取配置文件
     *
     * @return
     */
    private String[] getActiveProfile() {
        return this.applicationContext.getEnvironment().getActiveProfiles();
    }
}
